using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 挂载在mono上的单例模式
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
{

    private static T instance;
    private static bool initOk;
    public static T Instance
    {
        get
        {
            if (instance == null && !initOk)
            {
                var obj = FindObjectsOfType<T>();
                
                foreach (var t in obj)
                {
                    Destroy(t);
                }

               
                instance = new GameObject().AddComponent<T>();
                instance.name = "[" + typeof(T).ToString() + "]";
                DontDestroyOnLoad(instance);
                initOk = true;
                // 这里正确地调用Init()，因为instance已经被创建
                (instance as SingletonMono<T>)?.Init();
                
            }
            return instance;
        }
        private set { instance = value; }
    }

    /// <summary>
    /// 初始化
    /// </summary>
    protected  virtual void Init()
    {

    }


}
